<template>
    <div class="container">
        <div class="chart-container">
            <!-- 地图和侧边柱状图 -->
            <div style="width: 100%;height: 500px;">
                <div ref="mapChartContainer" style="width:70%;height: 160%;float: left;">
                </div>
                <div ref="mapAsideChartContainer"
                    style="width: 25%; height: 100%;float: left;top: 10%;"></div>
            </div>

            <!-- 岗位前十 -->
            <div style="width: 100%; height: 500px;padding-top: 10%;">
                <div ref="topSalaryChartContainer"
                    style="width:80%; height:100%;margin-bottom: 1%;float: left; position: relative; left: 10%;">
                </div>
            </div>

            <!-- 学历图和企业规模图 -->
            <div style="width: 100%; height: 700px;">
                <div ref="educationChartContainer" style="width:50%; height:100%;float: left;"></div>
                <div ref="scaleChartContainer" style="width:50%; height:80%;float: left;top: 10%;">
                </div>
            </div>
        </div>
    </div>
</template>
<style scoped>
.container {
    overflow: hidden;
}

/* 设置整体高度 */
/* .chart-container {
    height: 800px;
    overflow-y: scroll;
    overflow-x: hidden;
} */
</style>
<script setup>
import * as echarts from 'echarts';
import { onMounted, ref } from 'vue';
// import '/node_modules/echarts/map/js/china.js';
import 'echarts/map/js/china.js';
import analysis from '../../apis/analysis.js'

// 各个echarts图容器对象
const mapChartContainer = ref();
const mapAsideChartContainer = ref();
const topSalaryChartContainer = ref();
const educationChartContainer = ref();
const scaleChartContainer = ref();

// 获取岗位薪水前十数据
const position = ref([])
const avgSalary = ref([])
const getTopSalaryList = async () => {
    const res = await analysis.getSalaryTop()
    position.value = res.data.salaryTop.map(item => item.position)
    avgSalary.value = res.data.salaryTop.map(item => item.avgSalary)
}

// 获取不同学历的薪水和需求量数据
const education = ref([])
const educationPositionNum = ref([])
const educationAvgSalary = ref([])
const getEducationList = async () => {
    const res = await analysis.getEducationStatistic()
    education.value = res.data.statisticList.map(item => item.education)
    educationPositionNum.value = res.data.statisticList.map(item => item.positionNum)
    educationAvgSalary.value = res.data.statisticList.map(item => item.avgSalary)
}

// 获取企业规模环形图数据
const scale = ref([])
const scaleNum = ref([])
const scalePositionNum = ref([])
const scaleResult = ref([])
const getScaleList = async () => {
    const res = await analysis.getScaleStatistic()
    scale.value = res.data.scaleStatistic.map(item => item.scale)
    scaleNum.value = res.data.scaleStatistic.map(item => item.scaleNum)
    scalePositionNum.value = res.data.scaleStatistic.map(item => item.positionNum)
    // 将scale和scaleNum以json格式放入数组中 => data: [{ value: 114, name: '0-20人' },{ value: 930, name: '20-99人' }]
    scaleResult.value = scale.value.map((name, index) => ({
        value: scaleNum.value[index],
        name: name,
        positionNum: scalePositionNum.value[index]
    }));
}

// 获取省份统计数据
const allProvince = ref({})
const transformedPositionData = ref([])
const getProvinceList = async () => {
    const res = await analysis.getProvinceStatistic()
    console.log(res.data.analysisProvinceList)
    // 保存获取到的数据
    allProvince.value = res.data.analysisProvinceList
    res.data.analysisProvinceList.push({
        "id": 0,
        "province": "南海诸岛",
        "totalPosition": 0,
        "topPosition": "",
        "createTime": "2023-10-28T02:40:41.000+00:00",
        "updateTime": "2023-10-28T02:40:41.000+00:00"
    })
    transformedPositionData.value = res.data.analysisProvinceList.map(item => ({
        name: item.province,
        value: item.totalPosition
    }))
}

// 地图侧边top5柱状图
const clickProvince = ref('') // 点击地图后得到省份
const clickPositionData = ref([]) // x轴岗位名称数据
const clickNumData = ref([]) // y轴岗位数量数据
// 挂载完成后初始化
onMounted(async () => {
    // 赋值操作完成后再继续执行
    await getTopSalaryList()
    await getEducationList()
    await getScaleList()
    await getProvinceList()
    initMap()
    initTopEmploymentSalary()
    initEducationAndScale()
})

const initMap = () => {
    var mapChart = echarts.init(mapChartContainer.value);
    var mapAsideChart = echarts.init(mapAsideChartContainer.value);
    // 点击地图后，获取侧边的柱状图的数据并渲染
    mapChart.on('click', (param) => {
        clickProvince.value = param.name
        const find = allProvince.value.find(provinceData => provinceData.province === clickProvince.value);

        // 使用正则表达式替换所有单引号为双引号
        find.topPosition = find.topPosition.replace(/'/g, '"');
        // console.log("replacedString", find.topPosition);
        const topPositionObject = JSON.parse(find.topPosition);

        // clickPositionData.value = Object.keys(topPositionObject)
        mapAasideOption.xAxis.data = Object.keys(topPositionObject)
        // clickNumData.value = Object.values(topPositionObject)

        mapAasideOption.series[0].data = Object.values(topPositionObject)

        // console.log("key", clickPositionData.value)
        // console.log("value", clickNumData.value)
        console.log("xAxis", mapAasideOption.xAxis.data)
        console.log("series", mapAasideOption.series.data)
        mapAsideChart.setOption(mapAasideOption, true, true);


    })
    // 地图配置项
    const mapOption = {
        // geo配置，主要用于隐藏南海诸岛
        geo: [
            {
                // 地理坐标系组件
                map: "china",
                label: {
                    // 图形上的文本labels
                    normal: {
                        show: true,
                        textStyle: {
                            color: "rgba(0, 0, 0, 0.9)",
                            fontSize: '15'
                        }
                    },
                    emphasis: { // 高亮时样式
                        color: "#333"
                    }
                },
                // 这里是重点！！！
                regions: [
                    {
                        name: "南海诸岛",
                        itemStyle: {
                            // 隐藏地图
                            normal: {
                                opacity: 0, // 为 0 时不绘制该图形
                            }
                        },
                        label: {
                            show: false // 隐藏文字
                        }
                    }
                ],
                left: '25%',
            }
        ],
        title: {
            text: '全国各省岗位数量地图'
        },
        tooltip: {
            formatter: '{b}<br>岗位总数量: {c}'  // 提示框内容格式
        },
        // 侧边热力分布块
        visualMap: [{
            type: 'piecewise', // 分段型视觉映射components
            min: 0,
            max: 3000,
            splitNumber: 5,
            seriesIndex: 0, // 这里是设置视觉映射组件和哪个series关联，一般都是和第一个系列关联
            inRange: { // 通过 inRange 属性来设置数据范围内的颜色值
                color: ["#e0f3f8", "#abd9e9", "#74add1", "#4575b4", "#6495ED",]
            },
            textStyle: {
                color: '#000' // 文本样式
            },
            outOfRange: { color: '#fff' },// 设置底色
            left: 'left',
            top: '58%'
        }],
        series: [
            {
                name: '全国各省岗位数量分布图',
                type: 'map',
                mapType: 'china',
                roam: false,  // 禁止拖动和缩放
                label: {
                    show: true,
                    color: '#333'  // 城市名称文字color
                },
                // 省份名及其对应的岗位数量
                data: transformedPositionData.value,
                geoIndex: 0,
            },
        ],
    };

    // 地图侧边柱状图配置项
    var mapAasideOption = {
        title: {
            text: '省份top5岗位数量(点击地图后显示)'
        },
        grid: {
            left: "15%"
        },
        xAxis: {
            type: 'category',
            // data: ['数据分析', '数据开发', '数据采集', '数据挖掘', '大数据工程师'], // X 轴数据
            data: clickPositionData.value,
            // axisLabel: {
            //     rotate: 45, // 设置旋转角度为45度
            //     fontSize: '10'
            // },
            // x轴大于5个字的省略显示
            axisLabel: {
                rotate: 45,
                fontSize: '10',
                formatter: function (value, index) {
                    if (value.length > 8) {
                        return value.substr(0, 8) + '...'
                    } else {
                        return value
                    }
                }
            },
            splitLine: { show: false }
        },
        yAxis: {
            type: 'value'
        },
        tooltip: {
            trigger: 'axis', // 触发类型为坐标轴
            axisPointer: { // 坐标轴指示器配置项
                type: 'shadow' // 显示阴影
            },
        },
        series: [{
            name: '岗位数量',
            type: 'bar',
            // data: [10, 20, 30, 40, 50] // Y 轴数据
            data: clickNumData.value,
            itemStyle: {
                color: '#4b91e6'
            }
        }]
    };

    // 设置数据源
    mapOption && mapChart.setOption(mapOption);
    mapAasideOption && mapAsideChart.setOption(mapAasideOption)

}

// 岗位前十条形图
const initTopEmploymentSalary = () => {
    console.log("log:", position)
    var topSalaryChart = echarts.init(topSalaryChartContainer.value);
    // 设置option
    var topSalaryOption = {
        title: {
            text: '岗位薪水前十条型图',
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {

        },
        grid: {
            left: '5%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },

        xAxis: {
            type: 'value',
            splitLine: { show: false },
            axisLabel: {
                formatter: '{value} 元'
            },
        },
        yAxis: {
            type: 'category',
            data: position.value
        },
        series:
            [{
                name: '岗位薪水',
                type: 'bar',
                data: avgSalary.value,
                color: '#4b91e6'
            }]
    };
    topSalaryOption && topSalaryChart.setOption(topSalaryOption)

}
const initEducationAndScale = () => {
    var educationChart = echarts.init(educationChartContainer.value);
    var scaleChart = echarts.init(scaleChartContainer.value);
    const colors = ['#EE6666', '#4b91e6']
    // 设置option
    var educationOption = {
        color: colors,
        title: {
            text: '不同学历的薪水和需求量',
            textStyle: {
                fontSize: 18
            }
        },
        // 文本标题
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'none',
                crossStyle: {
                    color: "#999"
                }
                // 指示器类型,直线指示器
            }
        },
        // 触发类型：坐标轴触发，主要在柱状图，折线图等会使用类目轴的图表中使用
        toolbox: {
            feature: {
                dataView: { show: true, readOnly: false },
                magicType: { show: true, type: ['line', 'bar'] },
                // 动态类型切换
                restore: { show: true },
                // 配置项还原
                saveAsImage: { show: true }
            }
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 250,
            bottom: 50,
            data: ['平均薪水', '岗位需求量']
        },
        // 图例组件
        grid: {
            // 直角坐标系内绘图网格，
            left: '20%',
            // grid 组件离容器左侧的距离。
            right: '40%',
            // grid 组件离容器右侧的距离。
            bottom: '10%',
            // grid 组件离容器上侧的距离。
            containLable: true,
            tooltip: {
                axisPointer: {
                    type: 'none'
                }
            }
        },
        xAxis: [
            {
                type: 'category',
                data: education.value,
                axisPointer: {
                    type: 'shadow'
                },
                splitLine: { show: false },
                axisLabel: {
                    show: true,
                    margin: 6,
                    interval: 0,
                    rotate: -60,
                    inside: false
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '岗位需求量',
                // max: 15500,
                // min:50,
                axisLabel: {
                    formatter: '{value} 个'
                },
                splitLine: { show: false },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: colors[1]
                    }
                }
            },
            {
                type: 'value',
                name: '平均薪水',
                // max: 34000,
                splitLine: { show: false },
                axisLabel: {
                    formatter: '{value} 元 '
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: colors[0]
                    }
                }
            }
        ],
        series: [
            {
                name: '平均薪水',
                type: 'line',
                // stack:'Total',
                yAxisIndex: 1,
                tooltip: {
                    valueFormatter: function (value) {
                        return value + '元';
                    }
                },
                data: educationAvgSalary.value
            },
            {
                name: '岗位需求量',
                type: 'bar',
                tooltip: {
                    valueFormatter: function (value) {
                        return value + '个';
                    }
                },
                data: educationPositionNum.value
            }
        ],
    }
    var scaleOption = {
        title: {
            text: '招聘企业规模环形分布图'
        },
        // 文本标题
        tooltip: {
            trigger: 'item',
            // formatter: '{a} <br/>{b}: {c} ({d}%)'
            formatter: function (params) {
                return `公司规模: ${params.name}<br/>公司数量: ${params.value} (${params.percent}%)<br/>岗位数量: ${params.data.positionNum}`;
            }
        },
        // 触发类型：坐标轴触发，主要在柱状图，折线图等会使用类目轴的图表中使用
        legend: {
            top: '5%',
            left: 'right',
            // orient: 'vertical',
            // right: 25,
            top: 460,
            bottom: 120,
            // data: ['0-20人', '20-99人', '100-499人', '500-999人', '1000-9999人', '10000以上']
            data: scale.value
        },
        grid: {
            left: "10%"
        },
        series: [
            {
                name: '招聘企业规模环形分布图',
                type: 'pie',
                radius: ['35%', '60%'],
                center: ['50%', '50%'],
                avoidLabelOverlap: false,
                labelLine: {
                    show: false
                },
                // data: [
                //     { value: 114, name: '0-20人' },
                //     { value: 930, name: '20-99人' },
                //     { value: 1633, name: '100-499人' },
                //     { value: 659, name: '500-999人' },
                //     { value: 958, name: '1000-9999人' },
                //     { value: 281, name: '10000以上' }
                // ]
                data: scaleResult.value,
            },

        ],
    };

    // 绑定option
    educationOption && educationChart.setOption(educationOption)

    scaleOption && scaleChart.setOption(scaleOption)


}
</script>